package com.my.study.juc.basic.pattern.tuba;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Carlos
 * @version 1.0
 * @Description 缓冲区
 * @date 2021/4/11 20:33
 **/
public class SynContainer {

    private static final Logger LOGGER = LoggerFactory.getLogger(SynContainer.class);

    /**
     * 定义容器大小
     */
    private Chicken[] chickens = new Chicken[10];

    private int count;

    /**
     * 生产者放入产品
     *
     * @param chicken
     */
    public synchronized void push(Chicken chicken) {
        // 如果容器满了，就需要等待消费者消费
        if (count == chickens.length) {
            // 生产者等待
            try {
                System.out.println(Thread.currentThread().getName() + " push " + this);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        // 如果没满，就加入产品
        chickens[count++] = chicken;

        // 通过消费者消费
        this.notifyAll();
    }

    public synchronized Chicken pop() {
        if (count == 0) {
            try {
                System.out.println(Thread.currentThread().getName() + " pop " + this);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        count--;
        Chicken chicken = chickens[count];

        // 通过生产者生产
        this.notifyAll();
        return chicken;
    }

}
